/**
 * Copyright (c) 2005-2009 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: Struts2Utils.java 828 2010-01-03 14:00:35Z calvinxiu $
 */
package com.xinxi11.module.core.web.struts2;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.xinxi11.module.core.utils.ServletUtils;

/**
 * Struts2工具类.
 * 
 * 实现获取Request/Response/Session与绕过jsp/freemaker直接输出文本的简化函数.
 * 
 * @author calvin
 */
public class Struts2Utils {

	// -- header 常量定义 --//
	private static final String HEADER_ENCODING = "encoding";
	private static final String HEADER_NOCACHE = "no-cache";
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final boolean DEFAULT_NOCACHE = true;
	private static final String DEFAULT_DATEFORMAT = "yyyy-MM-dd";

	// -- content-type 常量定义 --//
	private static final String TEXT_TYPE = "text/plain";
	private static final String JSON_TYPE = "application/json";
	private static final String XML_TYPE = "text/xml";
	private static final String HTML_TYPE = "text/html";
	private static final String JS_TYPE = "text/javascript";

	// -- 取得Request/Response/Session的简化函数 --//
	/**
	 * 取得HttpSession的简化函数.
	 */
	public static HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}

	/**
	 * 取得HttpRequest的简化函数.
	 */
	public static HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 取得HttpResponse的简化函数.
	 */
	public static HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 获取request的头文件中的参数Referer中的queryString
	 * 
	 * @return Referer中的queryString
	 */
	public static String getRequestReferer() {
		String referer = Struts2Utils.getRequest().getHeader("Referer");
		return StringUtils.substringAfter(referer, "?");
	}

	/**
	 * 取得Request Parameter的简化方法.
	 */
	public static String getParameter(String name) {
		String result = ServletActionContext.getRequest().getParameter(name);
		if (StringUtils.isBlank(result)) {
			return null;
		}
		return result.trim();
	}

	/**
	 * 取得Request Parameter的简化方法.
	 */
	public static Integer getIntegerParameter(String name) {
		String result = getParameter(name);
		if (result == null) {
			return null;
		}
		return Integer.valueOf(result);
	}

	/**
	 * 取得Request Parameter的简化方法.
	 */
	public static Long getLongParameter(String name) {
		String result = getParameter(name);
		if (result == null) {
			return null;
		}
		return Long.valueOf(result);
	}

	/**
	 * 取得Request Parameter的简化方法.
	 */
	public static Double getDoubleParameter(String name) {
		String result = getParameter(name);
		if (result == null) {
			return null;
		}
		return Double.valueOf(result);
	}

	/**
	 * 取得Request Parameter的简化方法.
	 */
	public static Date getDateParameter(String name, String dateFormat) {
		try {
			String result = getParameter(name);
			if (result == null) {
				return null;
			}
			return new SimpleDateFormat(dateFormat).parse(result);
		} catch (ParseException e) {
		}
		return null;
	}

	public static Date getDateParameter(String name) {
		return getDateParameter(name, DEFAULT_DATEFORMAT);
	}

	public static void setAttribute(String name, Object obj) {
		ServletActionContext.getRequest().setAttribute(name, obj);
	}

	public static Object getAttribute(String name) {
		return ServletActionContext.getRequest().getAttribute(name);
	}

	public static Enumeration<?> getAttributeNames() {
		return ServletActionContext.getRequest().getAttributeNames();
	}

	// -- 绕过jsp/freemaker直接输出文本的函数 --//
	/**
	 * 直接输出内容的简便函数.
	 * 
	 * eg. render("text/plain", "hello", "encoding:GBK"); render("text/plain",
	 * "hello", "no-cache:false"); render("text/plain", "hello", "encoding:GBK",
	 * "no-cache:false");
	 * 
	 * @param headers
	 *            可变的header数组，目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true.
	 */
	public static void render(final String contentType, final String content, final String... headers) {
		HttpServletResponse response = initResponse(contentType, headers);
		try {
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 直接输出文本.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderText(final String text, final String... headers) {
		if (StringUtils.isNotBlank(text)) {
			render(TEXT_TYPE, text, headers);
		}
	}

	/**
	 * 直接输出HTML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderHtml(final String html, final String... headers) {
		if (StringUtils.isNotBlank(html)) {
			render(HTML_TYPE, html, headers);
		}
	}

	/**
	 * 直接输出XML.
	 * 
	 * @see #render(String, String, String...)
	 */
	public static void renderXml(final String xml, final String... headers) {
		if (StringUtils.isNotBlank(xml)) {
			render(XML_TYPE, xml, headers);
		}
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param jsonString
	 *            json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final String jsonString, final String... headers) {
		if (StringUtils.isNotBlank(jsonString)) {
			render(JSON_TYPE, jsonString, headers);
		}
	}

	/**
	 * 直接输出JSON,使用Jackson转换Java对象.
	 * 
	 * @param data
	 *            可以是List<POJO>, POJO[], POJO, 也可以Map名值对.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final Object data, final String... headers) {
		HttpServletResponse response = initResponse(JSON_TYPE, headers);
		try {
			response.getWriter().write(JSONObject.fromObject(data).toString());
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}

	/**
	 * 分析并设置contentType与headers.
	 */
	private static HttpServletResponse initResponse(final String contentType, final String... headers) {
		// 分析headers参数
		String encoding = DEFAULT_ENCODING;
		boolean noCache = DEFAULT_NOCACHE;
		for (String header : headers) {
			String headerName = StringUtils.substringBefore(header, ":");
			String headerValue = StringUtils.substringAfter(header, ":");

			if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
				encoding = headerValue;
			} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
				noCache = Boolean.parseBoolean(headerValue);
			} else {
				throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
			}
		}

		HttpServletResponse response = ServletActionContext.getResponse();

		// 设置headers参数
		String fullContentType = contentType + ";charset=" + encoding;
		response.setContentType(fullContentType);
		if (noCache) {
			ServletUtils.setNoCacheHeader(response);
		}

		return response;
	}

}
